﻿@using System.ComponentModel

<Table @ref="table"
       DataSource="@forecasts"
       Total="_total"
       @bind-PageIndex="_pageIndex"
       @bind-PageSize="_pageSize"
       OnPageIndexChange="async e=>await fetchData(e)"
       @bind-SelectedRows="selectedRows">
    <Selection Key="@(context.Id.ToString())" />
    <Column @bind-Field="@context.Id"/>
    <Column @bind-Field="@context.Date">
        @context.Date.ToShortDateString()
    </Column>
    <Column @bind-Field="@context.TemperatureC" />
    <Column Title="Temp. (F)" Field="@context.TemperatureF" />
    <Column @bind-Field="@context.Summary" />
</Table>

<br />
<p>pageIndex: @_pageIndex | pageSize: @_pageSize | Total: @_total</p>

<br />
<h5>selections:</h5>
@if (selectedRows != null && selectedRows.Any())
{
    <Button Danger Size="small" OnClick="@(e => { table.SetSelection(null); })">Clear</Button>

    @foreach (var selected in selectedRows)
    {
        <Tag @key="selected.Id" Closable OnClose="e=>RemoveSelection(selected.Id)">@selected.Id - @selected.Summary</Tag>
    }
}


@code {

    WeatherForecast[] forecasts;

    IEnumerable<WeatherForecast> selectedRows;
    ITable table;

    int _pageIndex = 1;
    int _pageSize = 10;
    int _total = 0;

    protected override async Task OnParametersSetAsync()
    {
        forecasts = await GetForecastAsync(1, 10);
        _total = 50;
    }

    async Task fetchData(PaginationEventArgs args)
    {
        forecasts = await GetForecastAsync(args.PageIndex, args.PageSize);
    }

    public class WeatherForecast
    {
        public int Id { get; set; }

        [DisplayName("Date")]
        public DateTime Date { get; set; }

        [DisplayName("Temp. (C)")]
        public int TemperatureC { get; set; }

        [DisplayName("Summary")]
        public string Summary { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    }

    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    public Task<WeatherForecast[]> GetForecastAsync(int pageIndex, int pageSize)
    {
        var rng = new Random();
        return Task.FromResult(Enumerable.Range((pageIndex - 1) * pageSize + 1, pageSize).Select(index => new WeatherForecast
        {
            Id = index,
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        }).ToArray());
    }

    public void RemoveSelection(int id)
    {
        var selected = selectedRows.Where(x => x.Id != id).ToList();
        table.SetSelection(selected.Select(x => x.Id.ToString()).ToArray());
    }
}
